#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QMessageBox>
const char GLJC[10] = {0x24,0x47,0x4c,0x4a,0x43,0x00,0x0c,0x00,0x00,0x00};
const char GPSZ[10] = {0x24,0x47,0x50,0x53,0x5a,0x00,0x0f,0x00,0x00,0x00};
const char AXIS[2] = {0x00,0x00};
const char TXSQ[10] = {0x24,0x54,0x58,0x53,0x51};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    auto list = m_serialClient.getAllSerialPort();
    for(auto item : list)
        ui->serial_box->addItem(item);
    ui->disconnect_btn->hide();
    connect(&m_serialClient,SIGNAL(signCPBJPrase()),                this,SLOT(onCPBJPrase()));
    connect(&m_serialClient,SIGNAL(signRecvData(QByteArray,bool)),       this,SLOT(slotRecvData(QByteArray,bool)));
    connect(&m_serialClient,SIGNAL(signPrase(PowerInfo)),           this,SLOT(onPrase(PowerInfo)));
    connect(&m_serialClient,SIGNAL(signPrase(GPSInfo)),             this,SLOT(onPrase(GPSInfo)));
    connect(&m_serialClient,SIGNAL(signPrase(CommunicationInfo)),   this,SLOT(onPrase(CommunicationInfo)));
    connect(ui->textEdit,&QTextEdit::textChanged,[=]{
        ui->textEdit->moveCursor(QTextCursor::End);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_connect_btn_clicked()
{
    if(ui->connect_btn->text() == "断开" ){
        on_disconnect_btn_clicked();
        ui->connect_btn->setText("连接");
        return;
    }
    QString portname = ui->serial_box->currentText();
    int rate = ui->rate_box->currentText().toUInt();
    int data = ui->bitlen_box->currentText().toUInt();
    int check = ui->check_box->currentText().toUInt();
    int stop = ui->stop_box->currentText().toUInt();
    auto status = m_serialClient.openSerialPort(portname,rate,data,check,stop);
    if(status){
        ui->connect_btn->setText("断开");
    }
}

void MainWindow::on_disconnect_btn_clicked()
{
    m_serialClient.disConnectSerialPort();
}

void MainWindow::on_power_detect_btn_clicked()
{
    QByteArray data;
    unsigned char checkOut = 0x00;
    for(int i = 0 ; i < 10 ; i++){
        checkOut ^= GLJC[i];
        data.append(GLJC[i]);
    }
    auto req = ui->power_send_outputFre->currentIndex();
    checkOut ^= (char)req;
    data.append((char)req);
    data.append(checkOut);
    sendData(data);
    slotRecvData(data);
}

void MainWindow::on_gps_set_btn_clicked()
{
    QByteArray data;
    unsigned char checkOut = 0x00;
    for(int i = 0 ; i < 10 ; i++){
        checkOut ^= GPSZ[i];
        data.append(GPSZ[i]);
    }
    auto req = ui->GPS_send_outControl->currentIndex();
    checkOut ^= (char)req;
    data.append((char)req);

    for(int i = 0 ; i < 2 ; i++){
        checkOut ^= AXIS[i];
        data.append(AXIS[i]);
    }

    req = ui->GPS_send_outfre->currentIndex();
    checkOut ^= (char)req;
    data.append((char)req);

    data.append(checkOut);
    sendData(data);
    slotRecvData(data);
}

void MainWindow::on_communication_set_btn_clicked()
{
    QByteArray data,test;
    unsigned char checkOut = 0x00;
    for(int i = 0 ; i < 5 ; i++){
        data.append(TXSQ[i]);
    }
    QString byteData = ui->communication_information_send->toPlainText().replace(" ","");
    int byteSize = byteData.size()/2;
    QString byteLen = QString::number(byteSize*8,16);
    if(byteLen.size() == 2)
        byteLen = "00"+byteLen;
    if(byteLen.size() == 3)
        byteLen = "0"+byteLen;
    ui->communication_information_send_infomationSize->setText(byteLen);
    QString len = QString::number(byteSize +18,16);
    if(len.size() == 2)
        len = "00"+len;
    if(len.size() == 3)
        len = "0"+len;
    QString targetArr = len + QString("000000")
            +ui->communication_information_send_infotype->text()
            +ui->communication_information_send_targetArr->text()
            + ui->communication_information_send_infomationSize->text()
            +"00"+byteData;
    QString cache;
    for(int i = 0; i<targetArr.size()-1; i+=2){
        cache.clear();
        test.clear();
        cache.append(targetArr.at(i));
        cache.append(targetArr.at(i + 1));
        test.append(cache.toInt(nullptr,16));
        data.append(test);
    }
    auto size_ = data.size();
    for(int i = 0 ; i <size_;i++){
        checkOut ^= data[i];
    }
    data.append(checkOut);
    sendData(data);
    slotRecvData(data);
}

void MainWindow::onReadyRead(QString)
{

}

void MainWindow::onCPBJPrase()
{
    if(ui->communication_rcve_isOverFre->isChecked())
        QMessageBox::critical(nullptr,"超频报警","超频报警");
}

void MainWindow::slotRecvData(QByteArray data , bool isSend)
{
    ui->textEdit->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz"));
    auto str = QString(data.toHex().toUpper());
    QString f;
    for(int i = 0 ; i<  str.size()-1 ; i+= 2){
        f += str.at(i);
        f += str.at(i+1);
        f += " ";
    }
    ui->textEdit->append( (isSend == 1? "send: " : "recv :") + f);
    ui->textEdit->append("");
}

void MainWindow::sendData(QByteArray data)
{
    qDebug()<<__FUNCTION__<<data;
    m_serialClient.sendData(data);
}

void MainWindow::onPrase(PowerInfo info)
{
    ui->power_rcve_updataTimePow->setText(info.updateTime);
    ui->power_rcve_pow1->setText(QString::number(info.power1));
    ui->power_rcve_pow2->setText(QString::number(info.power2));
    ui->power_rcve_pow3->setText(QString::number(info.power3));
    ui->power_rcve_pow4->setText(QString::number(info.power4));
    ui->power_rcve_pow5->setText(QString::number(info.power5));
    ui->power_rcve_pow6->setText(QString::number(info.power6));

}

void MainWindow::onPrase(GPSInfo info)
{
    ui->GPS_rcve_updataTimeGPS->setText(info.updateTime);
    ui->GPS_rcve_time->setText(info.time);
    ui->GPS_rcve_longitude->setText(info.longitude);
    ui->GPS_rcve_latitude->setText(info.latitude);
    ui->GPS_rcve_hight->setText(QString::number(info.hight));
    ui->GPS_rcve_speed->setText(QString::number(info.speed));
    ui->GPS_rcve_direction->setText(QString::number(info.direction));
    ui->GPS_rcve_moonNum->setText(QString::number(info.sateLiteNum));
    ui->GPS_rcve_status->setText(QString::number(info.status));
    ui->GPS_rcve_precision->setText(QString::number(info.precision));
    ui->GPS_rcve_error->setText(QString::number(info.deviation));

}

void MainWindow::onPrase(CommunicationInfo info)
{
    ui->communication_rcve_updataTimeCommunication->setText(info.updateTime);
    ui->communication_rcve_nfotype_2->setText(info.msgType);
    ui->communication_rcve_sendArr->setText(info.senderEndPointHex);
    ui->communication_rcve_sendTime->setText(info.sendTime);
    ui->communication_rcve_infosize->setText(info.recInfomationSize);
    ui->communication_rcve_info->setText(info.recInfomation);

    ui->communication_rcve_CRCcheck->setStyleSheet("border-radius:10px;border:1px solid black;background-color: "
                                                   + info.CRCStatus == 1 ? "rgb(255, 0, 0);":"rgb(170, 255, 127);");
}

void MainWindow::on_test_send_btn_clicked()
{
    QByteArray data,test;
    QString cache;
    unsigned char checkOut = 0x00;
    auto targetArr = ui->test_send_lineEdit->text().replace(" ","");
    for(int i = 0; i<targetArr.size()-1; i+=2){
        cache.clear();
        test.clear();
        cache.append(targetArr.at(i));
        cache.append(targetArr.at(i + 1));
        test.append(cache.toInt(nullptr,16));
        data.append(test);
    }
    auto size_ = data.size();
    for(int i = 0 ; i <size_;i++){
        checkOut ^= data[i];
    }
    data.append(checkOut);
    m_serialClient.sendData(data);
    slotRecvData(data);
}

void MainWindow::on_clear_cache_btn_clicked()
{
    m_serialClient.clearCache();
}
